import {Component, Input, OnInit} from '@angular/core';
import {SFSchema} from "@delon/form";
import {NzMessageService, NzModalRef, UploadFile} from "ng-zorro-antd";
import {AreaService} from "../../sys-setting/area-manage/area.service";
import {_HttpClient} from "@delon/theme";
import {ApiService} from "@core/services/api";
import {map} from "rxjs/operators";

function getBase64(file: File): Promise<string | ArrayBuffer | null> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
@Component({
  selector: 'app-house-edit',
  templateUrl: './house-edit.component.html',
  styles: [
    `::ng-deep .ant-select-selection__placeholder{
        color: rgba(0, 0, 0, 0.65);
    }`
  ]
})
export class HouseEditComponent implements OnInit {
  @Input()type: number; // 0 新增 1 修改
  @Input()set _param(value) {
    this.param = value;
    if (value.id) {
      this.fetchDetail(value.id);
    } else {
      this.showDetail = true;
    }

    console.log(this.fileList)
  }; // 参数
  
  param: any
  uploadUrl = '/network/minIo/uploadFile'
  showForm = false;
  showDetail = false;
  cityList: any;
  schema: SFSchema = {
    properties: {
      houseName: {
        type: 'string',
        title: '房屋名称',
        ui: {
          grid: {span: 12}
        }

      },
      houseAddress: {
        type: 'string',
        title: '房屋地址',
        ui: {
          grid: {span: 12}
        }
      },
      areaNumber: {
        type: 'string',
        title: '编号',
        maxLength:2,
        pattern:'[0-9]{2}',
        ui: {
          grid: {span: 12}
        }
      },
      houseType: {
        type: 'string',
        title: '房屋类型',
        enum: [
          {label: '出租屋', value:'1'},
          {label: '厂房', value:'2'},
          {label: '公寓', value: '3'},
          {label: '写字楼', value: '4'},
          {label: '商业住宅', value: '5'},
          {label: '其他', value: '6'},
        ],
        ui: {
          widget: 'select',

        }
      },
      houseFloors: {
        type: 'string',
        title: '层数',
        ui: {
          grid: {span: 12}
        }
      },
      houseRooms: {
        type: 'string',
        title: '房间数',
        ui: {
          grid: {span: 12}
        }
      },
     
      houseLng: {
        type: 'string',
        title: '经度',
        ui: {
          grid: {span: 12}
        }
      },
      houseLat: {
        type: 'string',
        title: '纬度',
        ui: {
          grid: {span: 12}
        }
      },
      areaId: {
        type: 'string',
        title: '所属区域',
        enum: [],
        ui: {
          widget: 'select',
          grid: {
            span: 24
          }
        }
      },
      status: {
        type: 'string',
        title: '状态',
        enum: [
          {label: '启用', value: true},
          {label: '停用', value: false},
        ],
        ui: {
          widget: 'select',

        }
      },
      houseRemark: {
        type: 'string',
        title: '备注',
        ui: {
          widget: 'textarea',
          autoSize: true,
          grid: {span: 24}
        }
      }

    },
    "ui": {
      "spanLabelFixed": 100,
      "grid": {
        "span": 12
      }
    },
    required: ['houseName','houseType', 'houseAddress', 'status', 'houseFloors', 'houseRooms', 'areaId']
  }
  submit(data: object): void {
    console.log(this.fileList)
    const url = this.type === 0 ? this.api.house.add.url : this.api.house.update.url+ `/${data['id']}`;
    const method = this.type === 0 ? this.api.house.add.method : this.api.house.update.method;
    data['areaAllId'] = data['areaId'];
    data['policeId'] = '0';
    data['policeAllId'] = '0';
    if (this.fileList.length> 0 && (this.fileList[0].response.status == '200' || this.fileList[0].url)) {
      data['houseImages'] =this.fileList[0].url ||  this.fileList[0].response.data;
    }
    this.http.request<any>(method, url, {body:data}).subscribe(res => {
      if (res.status === '201' || res.status === '200') {
        this.msg.success(res.message);
        this.modalRef.triggerOk();
      } else {
        this.msg.error(res.message)
      }
    })
  }
  fileList: any[] = [

  ];
  previewImage: string | undefined = '';
  previewVisible = false;

  handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }
    this.previewImage = file.url || file.preview;
    this.previewVisible = true;
  };
  fetchDetail(id) {
    this.http.get(this.api.house.getInfoById.url + `/${id}`).subscribe(res => {
      this.param = res.data;
      if(this.param.houseImages) {
        this.fileList = [...[{
          id: '-1',
          status: 'done',
          url: this.param.houseImages
        }]]
      }
      if (this.param.areaName) {
        this.schema.properties.areaId.ui['placeholder'] = this.param.areaName;
      }
      this.param.areaId = this.param.areaParentId;
      this.showDetail = true;
    })
  }
  feachCommunity(): void {
    this.http.post(this.api.area.list.url, {areaName: ''}).subscribe((res: any) => {
      if (res.status == '200') {
        this.schema.properties.areaId.enum = res.data.map(item => {
          return {
            label: item.areaName,
            value: item.id
          }
        });
        this.showForm = true;
      }
    })
  }
  constructor(
    private msg: NzMessageService,
    private modalRef: NzModalRef,
    private area: AreaService,
    private http: _HttpClient,
    private api: ApiService
  ) { }
  ngOnInit() {
    this.feachCommunity();
    /*this.area.getAreaTreeNode(0).then(
      res => {
        this.schema.properties.areaId.enum = res.map(item => {
          item.disabled = true;
          return item
        });
        if (this.type == 3) {
          /!*for (const i in this.schema.properties) {
            this.schema.properties[i]['readOnly'] = true;
          }*!/
          this.schema.readOnly = true;
        }
        this.showForm = true;
      }
    )*/
  }

}
